package com.ias.agdis_r.activity;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
//import android.support.v4.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentPagerAdapter;
//import android.support.v4.view.ViewPager;
import androidx.viewpager.widget.ViewPager;
//import android.support.v4.view.ViewPager.OnPageChangeListener;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.fragment.box.BoxTabFlight;
import com.ias.agdis_r.fragment.box.BoxTabMessage;
import com.ias.agdis_r.fragment.box.BoxTabTask;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.view.BadgeView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息盒子界面
 *
 * @author guoxr
 */
public class BoxActivity extends BaseFragmentActivity implements
        OnClickListener {

    public BoxActivity() {
        super();
        //保存BoxActivity
        DataBaseManager.getInstance().setBoxActivty(this);
        // TODO Auto-generated constructor stub
    }

    private AlertDialog dialog;
    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    public static int LOARMORE = 10;// 消息盒子每次加载历史数据的数量
    public static List<String[]> taskNo = new ArrayList<String[]>();
    public static List<String[]> flightNo = new ArrayList<String[]>();
    public static List<String[]> messageNo = new ArrayList<String[]>();
    private String enb = JavaBeanManager.getInstance().getUserinfo().getEnb();
    private boolean messageRefresh = true, ignore = true;
    /**
     * 三个Fragment
     */
    private BaseFragment boxTask;
    private BaseFragment boxFlight;
    private BaseFragment boxMessage;

    /**
     * 顶部三个LinearLayout
     */
    private LinearLayout mTabTask;
    private LinearLayout mTabFlight;
    private LinearLayout mTabMessage;

    /**
     * 顶部的三个TextView
     */
    private TextView mTask;
    private TextView mFlight;
    private TextView mMessage;

    /**
     * 分别为每个TabIndicator创建一个BadgeView
     */
    private BadgeView mBadgeViewforTask;
    private BadgeView mBadgeViewforFlight;
    private BadgeView mBadgeViewforMessage;

    /**
     * Tab的那个引导线
     */
    private ImageView mTabLine;
    /**
     * ViewPager的当前选中页
     */
    private int currentIndex = JavaBeanManager.getInstance().getUserinfo()
            .getCurrentIndex();
    /**
     * 屏幕的宽度
     */
    private int screenWidth;
    private ActionBar actionBar;
    private int task, flight, message;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_box);
        Intent intent = getIntent();
        if(intent!=null){
            String type = S.valueOf(intent.getStringExtra(MessageModel.REFRESH_BOX_TYPE));
            int index = initSelectedType(type);
            currentIndex = index;
        }
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        mViewPager.setOffscreenPageLimit(2);
        actionBar = getActionBar();
        BoxActionBar();
        if (S.isNotEmpty(enb)) {
            initTaskData();
            initFlightData();
            initMessageData();
        }
        initView();
        initTabLine(currentIndex);
        /**
         * 设置监听
         */
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // 重置所有TextView的字体颜色
                resetTextView();
                switch (position) {
                    case 0:
                        mTabTask.removeView(mBadgeViewforTask);
                        mBadgeViewforTask.setBadgeCount(task);
                        mTabTask.addView(mBadgeViewforTask);
                        mTask.setTextColor(getResources().getColor(R.color.green));
                        break;
                    case 1:
                        mTabFlight.removeView(mBadgeViewforFlight);
                        mBadgeViewforFlight.setBadgeCount(flight);
                        mTabFlight.addView(mBadgeViewforFlight);
                        mFlight.setTextColor(getResources().getColor(R.color.green));
                        break;
                    case 2:
                        mTabMessage.removeView(mBadgeViewforMessage);
                        mBadgeViewforMessage.setBadgeCount(message);
                        mTabMessage.addView(mBadgeViewforMessage);
                        mMessage.setTextColor(getResources()
                                .getColor(R.color.green));
                        break;
                }
                currentIndex = position;
                JavaBeanManager.getInstance().getUserinfo()
                        .setCurrentIndex(currentIndex);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                /**
                 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
                 * 然后改变根据positionOffset动态改变TabLine的leftMargin
                 */
                if (currentIndex == 0 && position == 0)// 0->1
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (positionOffset
                            * (screenWidth * 1.0 / 3) + currentIndex
                            * (screenWidth / 3));
                    mTabLine.setLayoutParams(lp);

                } else if (currentIndex == 1 && position == 0) // 1->0
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (-(1 - positionOffset)
                            * (screenWidth * 1.0 / 3) + currentIndex
                            * (screenWidth / 3));
                    mTabLine.setLayoutParams(lp);
                } else if (currentIndex == 1 && position == 1) // 1->2
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (positionOffset
                            * (screenWidth * 1.0 / 3) + currentIndex
                            * (screenWidth / 3));
                    mTabLine.setLayoutParams(lp);
                } else if (currentIndex == 2 && position == 1) // 2->1
                {
                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                            .getLayoutParams();
                    lp.leftMargin = (int) (-(1 - positionOffset)
                            * (screenWidth * 1.0 / 3) + currentIndex
                            * (screenWidth / 3));
                    mTabLine.setLayoutParams(lp);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        if (currentIndex == -1) {
            mViewPager.setCurrentItem(1);
            JavaBeanManager.getInstance().getUserinfo().setCurrentIndex(1);
        } else {
            // 当currentIndex为0时启动activity不执行onPageSelected
            if (currentIndex == 0) {
                mTabTask.removeView(mBadgeViewforTask);
                mBadgeViewforTask.setBadgeCount(task);
                mTabTask.addView(mBadgeViewforTask);
                mTask.setTextColor(getResources().getColor(R.color.green));
            }
            mViewPager.setCurrentItem(currentIndex);
        }
    }

    private void initTaskData() {
        // TODO Auto-generated method stub
        if (enb != null) {
            BoxDBHelper dbHelper = new BoxDBHelper(this);
            List<Map<String, Object>> list = dbHelper.getData(
                    BoxDBHelper.TABLE_TASK, new String[]{"_id", "tnb", "msg",
                            "type", "time", "ischeck"}, "enb='" + enb +"'",
                    "time desc");
            dbHelper.closeDB();
            DataManager.getInstance().setTaskChangeList(list);
            task = DataManager.getInstance().getListCheckNumber(
                    DataManager.getInstance().getTaskChangeList());
        } else {
            DataManager.getInstance().setTaskChangeList(null);
        }
    }

    private void initFlightData() {
        // TODO Auto-generated method stub
        if (enb != null) {
            BoxDBHelper dbHelper = new BoxDBHelper(this);
            List<Map<String, Object>> list = dbHelper.getData(
                    BoxDBHelper.TABLE_FLIGHT, new String[]{"_id", "fke",
                            "msg", "type", "time", "ischeck"}, "enb='" + enb +"'",
                    "time desc");
            dbHelper.closeDB();
            DataManager.getInstance().setFlightChangeList(list);
            flight = DataManager.getInstance().getListCheckNumber(
                    DataManager.getInstance().getFlightChangeList());
        } else {
            DataManager.getInstance().setFlightChangeList(null);
        }
    }

    private void initMessageData() {
        // TODO Auto-generated method stub
        if (enb != null) {
            BoxDBHelper dbHelper = new BoxDBHelper(this);
            List<Map<String, Object>> list = dbHelper.getData(
                    BoxDBHelper.TABLE_MESSAGE, new String[]{"_id", "tgn",
                            "sem", "mtn", "txt", "stm", "readed"},
                    "sem is not '' and user_name ='" + enb +"'", "stm desc");
            dbHelper.closeDB();
            DataManager.getInstance().setMessageList(list);
            message = DataManager.getInstance().getMessageReadedNumber(
                    DataManager.getInstance().getMessageList());
        } else {
            DataManager.getInstance().setMessageList(null);
        }
    }

    /**
     * 重置颜色
     */
    protected void resetTextView() {
        mTask.setTextColor(getResources().getColor(R.color.black));
        mFlight.setTextColor(getResources().getColor(R.color.black));
        mMessage.setTextColor(getResources().getColor(R.color.black));
    }

    /**
     * 初始化控件，初始化Fragment
     */
    private void initView() {
        mTabTask = (LinearLayout) findViewById(R.id.id_tab_task);
        mTabFlight = (LinearLayout) findViewById(R.id.id_tab_flight);
        mTabMessage = (LinearLayout) findViewById(R.id.id_tab_message);
        mTabTask.setOnClickListener(this);
        mTabFlight.setOnClickListener(this);
        mTabMessage.setOnClickListener(this);

        mTask = (TextView) findViewById(R.id.id_task);
        mFlight = (TextView) findViewById(R.id.id_flight);
        mMessage = (TextView) findViewById(R.id.id_message);

        boxTask = new BoxTabTask();
        boxFlight = new BoxTabFlight();
        boxMessage = new BoxTabMessage();
        mFragments.add(boxTask);
        mFragments.add(boxFlight);
        mFragments.add(boxMessage);

        mBadgeViewforTask = new BadgeView(this);
        mBadgeViewforFlight = new BadgeView(this);
        mBadgeViewforMessage = new BadgeView(this);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };
        mViewPager.setAdapter(mAdapter);

        mBadgeViewforTask.setBadgeCount(task);
        mTabTask.addView(mBadgeViewforTask);

        mBadgeViewforFlight.setBadgeCount(flight);
        mTabFlight.addView(mBadgeViewforFlight);

        mBadgeViewforMessage.setBadgeCount(message);
        mTabMessage.addView(mBadgeViewforMessage);
    }

    /**
     * 根据屏幕的宽度，初始化引导线的宽度
     *
     * @param page
     */
    private void initTabLine(int page) {
        mTabLine = (ImageView) findViewById(R.id.id_tab_line);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(outMetrics);
        screenWidth = outMetrics.widthPixels;
        LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
                .getLayoutParams();
        lp.width = screenWidth / 3;
        if (page != -1) {
            lp.leftMargin = (int) (screenWidth * 1.0 / 3) * page;
            mTabLine.setLayoutParams(lp);
        } else {
            mTabLine.setLayoutParams(lp);
        }
    }

    private void BoxActionBar() {
        actionBar.setCustomView(LayoutInflater.from(BoxActivity.this).inflate(
                R.layout.actionbar_box, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        ImageView back = (ImageView) findViewById(R.id.actionbar_box_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        ImageView ignore = (ImageView) findViewById(R.id.iv_refresh);
        ignore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                showIgnoreDialog();
            }
        });
    }

    private void showIgnoreDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(BoxActivity.this);
        builder.setTitle(R.string.prompt);
        builder.setMessage(getString(R.string.isIgnore));
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ignore(ignore);
            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        dialog = builder.create();
        dialog.show();
    }

    private void ignore(boolean mignore) {
        if (mignore) {
            ignore = false;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 显示进度条
                    ActionManager.getInstance().showProgress();
                    // 忽略所有消息
                    BoxDBHelper dbHelper = new BoxDBHelper(BoxActivity.this);
                    for (int i = 0; i < taskNo.size(); i++) {
                        dbHelper.setIgnore(BoxDBHelper.TABLE_TASK, "ischeck",
                                taskNo.get(i));
                    }
                    for (int i = 0; i < flightNo.size(); i++) {
                        dbHelper.setIgnore(BoxDBHelper.TABLE_FLIGHT, "ischeck",
                                flightNo.get(i));
                    }
                    for (int i = 0; i < messageNo.size(); i++) {
                        dbHelper.setIgnoreMessage(BoxDBHelper.TABLE_MESSAGE, "readed",
                                messageNo.get(i));
                    }
                    dbHelper.closeDB();
                    ignore = true;
                    // 显示进度条
                    ActionManager.getInstance().hideProgress();
                    ActionManager.getInstance().updateUI("ignore");
                }
            }).start();
        }
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        // 清空保存的BoxActivity
        DataBaseManager.getInstance().setBoxActivty(null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_tab_task:
                mViewPager.setCurrentItem(0);
                break;
            case R.id.id_tab_flight:
                mViewPager.setCurrentItem(1);
                break;
            case R.id.id_tab_message:
                mViewPager.setCurrentItem(2);
                break;
        }
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub

    }

    /**
     * 弹窗后初始化显示TAB类型
     * @param tag
     */
    private int initSelectedType(String tag){
        if (tag.equals(MessageModel.REFRESH)) {
            JavaBeanManager.getInstance().getUserinfo()
                    .setCurrentIndex(0);
            return 0;
        }
        else if (tag.equals(MessageModel.REFRESH_BOXFLIGHT)) {
            JavaBeanManager.getInstance().getUserinfo()
                    .setCurrentIndex(1);
            return 1;
        }
        else if (tag.equals(MessageModel.REFRESH_BOXMESSAGE)) {
            JavaBeanManager.getInstance().getUserinfo()
                    .setCurrentIndex(2);
            return 2;
        }
        return -1;
    }
    @Override
    public void updateUI(String tag) {
        // TODO Auto-generated method stub
        if (tag.equals(MessageModel.REFRESH)) {
            initTaskData();
            // 更新任务列表的BadgeView
            mTabTask.removeView(mBadgeViewforTask);
            mBadgeViewforTask.setBadgeCount(task);
            mTabTask.addView(mBadgeViewforTask);
            boxTask.updateUI("BoxTabTask");
        }
        if (tag.equals(MessageModel.REFRESH_BOXFLIGHT)) {
            initFlightData();
            // 更新航班列表的BadgeView
            mTabFlight.removeView(mBadgeViewforFlight);
            mBadgeViewforFlight.setBadgeCount(flight);
            mTabFlight.addView(mBadgeViewforFlight);
            boxFlight.updateUI("BoxTabFlight");
        }
        if (tag.equals(MessageModel.REFRESH_BOXMESSAGE)) {
            if (messageRefresh) {
                messageRefresh = false;
                new MyThreadMessage().start();
            }
        }
        if (tag.equals("ThreadMessage")) {
            initMessageData();
            // 更新航班列表的BadgeView
            mTabMessage.removeView(mBadgeViewforMessage);
            mBadgeViewforMessage.setBadgeCount(message);
            mTabMessage.addView(mBadgeViewforMessage);
            boxMessage.updateUI("BoxTabMessage");
        }
        if (tag.equals("ignore")) {
            updateUI(MessageModel.REFRESH);
            updateUI(MessageModel.REFRESH_BOXFLIGHT);
            updateUI("ThreadMessage");
        }
    }

    public class MyThreadMessage extends Thread {
        public void run() {
            try {
                MyThreadMessage.sleep(1000);
                ActionManager.getInstance().updateUI("ThreadMessage");
                messageRefresh = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void showProgress() {
        super.showProgress();
    }

    @Override
    protected void hideProgress() {
        super.hideProgress();
    }
}
